package han.chensing.latos.game.util;

import java.io.IOException;
import java.io.InputStream;

public class ByteDataStreamReader {
    private final byte[] data;
    private final char[] module;
    private int moduleIndex;
    private int offset;
    private int floatDivide;

    public ByteDataStreamReader(byte[] data,char[] module){
        this.data=data;
        this.offset=0;
        this.module=module;
        this.moduleIndex=0;
        this.floatDivide=5;
    }
    public ByteDataStreamReader(byte[] data){
        this(data, (char[]) null);
    }
    public ByteDataStreamReader(byte[] data,String module){
        this(data,module.toCharArray());
    }

    public int nextInt(){
        int i = ByteUtil.bytesToInt(data, offset);
        offset+=4;
        return i;
    }

    public long nextLong(){
        long l = ByteUtil.bytesToLong(data, offset);
        offset+=8;
        return l;
    }

    public float nextFloat(){
        return nextLong()/(float)Math.pow(10,floatDivide);
    }

    public short nextShort(){
        short i = ByteUtil.bytesToShort(data, offset);
        offset+=2;
        return i;
    }

    public byte nextByte(){
        if (offset>=data.length)
            return 0;
        byte datum = data[offset];
        offset++;
        return datum;
    }

    public void setFloatDivide(int floatDivide) {
        this.floatDivide = floatDivide;
    }

    public Object next(){
        if (module==null)
            return 0;
        if (module.length==moduleIndex)
            return 0;
        char c = module[moduleIndex++];
        return nextAType(c);
    }

    public Object nextAType(char c){
        switch (c){
            case 'L':
            case 'l':
                return nextLong();
            case 'i':
            case 'I':
                return nextInt();
            case 'f':
            case 'F':
                return nextFloat();
            case 's':
            case 'S':
                return nextShort();
            case 'b':
            case 'B':
                return nextByte();
        }
        return 0;
    }
}
